<?php

// @author 3ogx <3ogx.com@gmail.com>

namespace Jushuitan;

use GuzzleHttp\Client;

class RefreshToken
{
    use ErpHelpTrait;

    // 沙箱环境
    public $url = 'https://openapi.jushuitan.com/openWeb/auth/refreshToken';

    // 正式环境
    // public $url = 'https://openapi.jushuitan.com/openWeb/auth/refreshToken';

    /**
     * RefreshToken constructor.
     */
    public function __construct($config)
    {
        $this->secret = $config['app_secret'];
        $this->params = [
            'app_key'       => $config['app_key'],
            'grant_type'    => 'refresh_token',
            'charset'       => 'utf-8',
            'refresh_token' => $config['refresh_token'],
            'scope'         => 'all',
            'timestamp'     => now()->timestamp,
        ];
    }

    /**
     * @param array $data
     *
     * @return \Psr\Http\Message\StreamInterface
     *
     * @throws ErpException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function send($data = [])
    {
        $params                = array_replace_recursive($this->params, $data);
        $params['sign']        = $this->getSign($this->secret, $params);
        $params['form_params'] = $params;
        $params['headers']     = ['Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'];

        $client   = new Client(['base_uri' => $this->url]);
        $response = $client->request('POST', $this->url, $params);
        $data     = json_decode($response->getBody(), true);
        if (0 === $data['code']) {
            return $data;
        }

        throw new ErpException(sprintf('请求失败！错误信息：%s, 错误编码： %s', $data['msg'], $data['code']));
    }
}
